package com.kl.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;


@Component
public class CurrentLock {
    @Autowired
    private RedisTemplate redisTemplate;

    private Logger logger = LoggerFactory.getLogger(CurrentLock.class);

    //枷锁
    public boolean lock(String key ,String value){
        if(redisTemplate.boundValueOps(key).setIfAbsent(value)){
            //枷锁成功
            return true;
        }
        //已经被锁
        //判断上一个锁是否超时
        String o = (String)redisTemplate.boundValueOps(key).get();
        if(o!=null && Long.parseLong(o)<new Date().getTime()){
            String andSet = (String)redisTemplate.boundValueOps(key).getAndSet(value);
            if(Objects.equals(o,andSet)){
                return true;
            }
        }
        return false;
    }
    //解锁
    public boolean unlock(String key,String value){
        String o =(String) redisTemplate.boundValueOps(key).get();
        if(o!=null && o.equals(value)){
            redisTemplate.delete(key);//解锁
        }
        return true;
    }
}
